// 三测单录入数据页
<template>
  <van-nav-bar
    :title="title"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  >
    <template #right>
      <van-icon name="sign" @click="savelist" />
    </template>
  </van-nav-bar>
  <van-row align="center">
    <van-col span="11">
      <!-- 输入框与触发按钮 -->
      <van-cell-group inset>
        <van-field
          v-model="selectedDateTime"
          label="录入时间"
          readonly
          placeholder="请选择日期和时间"
          @click="showPicker = true"
        />
      </van-cell-group>

      <!-- 弹出层与选择器 -->
      <van-popup
        v-model:show="showPicker"
        position="bottom"
        :style="{ height: '50%' }"
      >
        <van-picker-group
          title="录入日期"
          :tabs="['选择日期', '选择时间']"
          @confirm="onConfirm"
          @cancel="onCancel"
        >
          <van-date-picker v-model="currentDate" />
          <van-time-picker v-model="currentTime" />
        </van-picker-group>
      </van-popup>
    </van-col>
    <van-col span="8">
      <van-space size="2rem">
        <van-button type="primary" size="mini" @click="tolishi"
          >历史</van-button
        >
        <van-button type="primary" size="mini" @click="tosancedan"
          >三测单</van-button
        >
      </van-space>
    </van-col>
    <van-col span="6"></van-col>
  </van-row>
  <!-- 表头 -->
  <van-cell>
    <template #title>
      <van-row>
        <van-col span="6">类别</van-col>
        <van-col span="6">方式</van-col>
        <van-col span="6">检查值</van-col>
        <van-col span="6">管理</van-col>
      </van-row>
    </template>
  </van-cell>

  <!-- 表格内容 -->
  <van-cell-group>
    <van-cell v-for="(item, index) in list" :key="index">
      <template #title>
        <van-row>
          <!-- 添加 offset 控制左侧间距 -->
          <van-col span="6" offset="0">{{ item.type }}</van-col>
          <van-col span="6" offset="0">{{ item.way }}</van-col>
          <van-col span="6" offset="0">{{ item.value + item.unit }}</van-col>
          <van-col span="6" offset="0">
            <van-button size="mini" @click="handledel(item)">删除</van-button>
          </van-col>
        </van-row>
      </template>
    </van-cell>
  </van-cell-group>
  <van-back-top offset @click="additem">
    <van-icon name="plus" />
  </van-back-top>
  <van-action-sheet v-model:show="show">
    <van-tabs v-model:active="active" animated @change="onChange">
      <van-tab title="体温">
        <van-form>
          <van-cell-group inset>
            <van-field
              v-model="fromvalue"
              name="检查值"
              label="检查值"
              placeholder="检查值"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入合理范围之内的数值（35~42）',
                },
              ]"
              ref="tw"
            />
            <van-field v-model="fromunit" name="单位" label="单位" readonly />
          </van-cell-group>
        </van-form>
      </van-tab>
      <van-tab title="脉搏">
        <van-form>
          <van-cell-group inset>
            <van-field
              v-model="fromvalue"
              name="检查值"
              label="检查值"
              placeholder="检查值"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入合理范围之内的数值（35~42）',
                },
              ]"
              ref="mb"
            />
            <van-field v-model="fromunit" name="单位" label="单位" readonly />
          </van-cell-group>
        </van-form>
      </van-tab>
      <van-tab title="呼吸">
        <van-form>
          <van-cell-group inset>
            <van-field
              v-model="fromvalue"
              name="检查值"
              label="检查值"
              placeholder="检查值"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入合理范围之内的数值（35~42）',
                },
              ]"
              ref="hx"
            />
            <van-field v-model="fromunit" name="单位" label="单位" readonly />
          </van-cell-group>
        </van-form>
      </van-tab>
    </van-tabs>
    <van-cell>
      <!-- 使用 title 插槽来自定义标题 -->
      <template #value>
        <van-button type="primary" size="large" @click="onSubmit"
          >添加</van-button
        >
      </template>
    </van-cell>
  </van-action-sheet>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { reactive, ref, onMounted } from "vue";
import { batchadd } from "../api/sign";
const router = useRouter();

const selectitem = JSON.parse(localStorage.getItem("selectitem"));
const title = selectitem.name + selectitem.age + "岁";

onMounted(() => {
  if (localStorage.getItem("fromlist")) {
    list.push(...JSON.parse(localStorage.getItem("fromlist")));
    localStorage.removeItem("fromlist");
  }
});

function onClickLeft() {
  console.log("onClickLeft");
  if (list.length > 0) {
    showNotify({
      duration: 800,
      type: "warning",
      position: "bottom",
      message: "有未保存的数据",
    });
    return false;
  }
  //返回上一页
  router.back();
}

const list = reactive([]);

const showPicker = ref(false);
let selectedDateTime = ref("");
const now = new Date();
const currentDate = ref([
  now.getFullYear().toString(),
  (now.getMonth() + 1).toString().padStart(2, "0"),
  now.getDate().toString().padStart(2, "0"),
]);
const currentTime = ref([now.getHours().toString().padStart(2, "0"), "00"]);

const onConfirm = () => {
  // showToast(`${currentDate.value.join("/")} ${currentTime.value.join(":")}`);
  selectedDateTime.value = `${currentDate.value.join(
    "/"
  )} ${currentTime.value.join(":")}`;
  showPicker.value = false;
};

const onCancel = () => {
  showPicker.value = false;
};

function tolishi() {
  if (list.length > 0) {
    localStorage.setItem("fromlist", JSON.stringify(list));
  }
  router.push("/SignHistoryData");
}
function tosancedan() {
  if (list.length > 0) {
    localStorage.setItem("fromlist", JSON.stringify(list));
  }
  router.push("/TriadView");
}

function additem() {
  if (!selectedDateTime.value?.trim()) {
    showNotify({
      type: "warning",
      duration: 800,
      message: "先选择录入时间",
    });
    showPicker.value = true;
    // return false;
  }
  // list.push({ name: "赵六", age: 18 });
  show.value = true;
}

const show = ref(false);
let fromvalue = ref("");
let fromunit = ref("℃");
const active = ref(0);
const onSubmit = (values) => {
  console.log("submit", active.value);
  console.log("submit", selectedDateTime.value);
  if (!fromvalue.value) {
    showNotify({
      type: "warning",
      message: "请输入检查值",
    });
    return false;
  }
  if (active.value == 0) {
    list.push({
      type: "体温",
      way: "腋下",
      value: fromvalue.value,
      unit: fromunit.value,
      patientregid: selectitem.id,
      measuredate: selectedDateTime.value.slice(0, 10).replace(/\//g, "-"),
      timepoint: selectedDateTime.value.slice(11, 13),
    });
    showNotify({ type: "success", duration: 800, message: "添加成功" });
    fromvalue.value = "";
  } else if (active.value == 1) {
    list.push({
      type: "脉搏",
      way: "腕动脉",
      value: fromvalue.value,
      unit: fromunit.value,
      patientregid: selectitem.id,
      measuredate: selectedDateTime.value.slice(0, 10).replace(/\//g, "-"),
      timepoint: selectedDateTime.value.slice(11, 13),
    });
    showNotify({ type: "success", duration: 800, message: "添加成功" });
    fromvalue.value = "";
  } else if (active.value == 2) {
    list.push({
      type: "呼吸",
      way: "呼吸",
      value: fromvalue.value,
      unit: fromunit.value,
      patientregid: selectitem.id,
      measuredate: selectedDateTime.value.slice(0, 10).replace(/\//g, "-"),
      timepoint: selectedDateTime.value.slice(11, 13),
    });
    showNotify({ type: "success", duration: 800, message: "添加成功" });
    fromvalue.value = "";
  }
  // show.value = false;
};
let tw = ref(null);
let mb = ref(null);
let hx = ref(null);
function onChange(index) {
  if (index == 0) {
    fromunit.value = "℃";
    //光标选中
    //延迟获取焦点
    setTimeout(() => {
      tw.value.focus();
    }, 500);
  } else if (index == 1) {
    fromunit.value = "次/分";
    setTimeout(() => {
      mb.value.focus();
    }, 500);
  } else if (index == 2) {
    fromunit.value = "次/分";
    setTimeout(() => {
      hx.value.focus();
    }, 500);
  }
  fromvalue.value = "";
}

function handledel(item) {
  console.log("handledel", item);
  list.splice(list.indexOf(item), 1);
}

function savelist() {
  console.log("savelist");
  console.log(list);
  if (list.length == 0) {
    showNotify({
      type: "warning",
      position: "bottom",
      message: "请先添加数据",
    });
    return false;
  }
  batchadd({ signList: list }).then((res) => {
    console.log(res);
    list.splice(0, list.length);
    showNotify({ type: "success", position: "bottom", message: "保存成功" });
  });
}
</script>

<style scoped>
/* 表格样式 */
.table-header {
  padding: 12px;
  background: #f7f8fa;
  font-weight: bold;
  border-bottom: 1px solid #ebedf0;
}
</style>
